//
//  ViewController.m
//  SuoSiApp
//
//  Created by zhang on 16/3/31.
//  Copyright © 2016年 Ym. All rights reserved.
//


#import "BSUIUserInfoBase.h"
#import "BSMainInterfaceViewControllerViewController.h"
#import "ViewController.h"
#import "BSRegisterViewController.h"
#import "AFNetworking.h"
#import <CoreLocation/CoreLocation.h>
#import <FMDB.h>


@interface ViewController ()<MKMapViewDelegate, CLLocationManagerDelegate>
//
//声明一个位置管理对象
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic,strong) FMDatabase *db;

@property (nonatomic, assign) BOOL isLogin;
@property (nonatomic, assign)  BOOL isExist ;


//定位获得的精度  和  纬度
@property (nonatomic, strong)NSString *latitude, *longitude;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    NSLog(@"kuan %f, gao %f",kScrenWidth,kScrenHeight);
    

    
    _isLogin = NO;
    
    self.navigationController.navigationBar.hidden = YES;
    self.loginView = [[BSLoginView alloc]initWithFrame:self.view.bounds];
    [self.loginView.rememberBT addTarget:self action:@selector(rememberBTClict) forControlEvents:(UIControlEventTouchUpInside)];
    [self.loginView.loginBT addTarget:self action:@selector(loginClict) forControlEvents:(UIControlEventTouchUpInside)];
    [self.loginView.registerBT addTarget:self action:@selector(registerBTClict) forControlEvents:(UIControlEventTouchUpInside)];
    [self.loginView.forgetPasswordBT addTarget:self action:@selector(forgetPassword) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:self.loginView];
    

    

//  启动定位

    //添加手势
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tap1.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap1];
#pragma mark 获取网络状态
    [self AFNetworkStatus];
//    获取个人信息 得到个人姓名
    

}
-(void)viewTapped:(UITapGestureRecognizer*)tap1
{
    
    [self.view endEditing:YES];
}




- (void)loginClict1{

//    SuanfaViewController *sVC = [[SuanfaViewController alloc]init];
//    [self.navigationController pushViewController:sVC animated:YES];
}
- (void)getLocationCoordinate{
    


    _mapView = [[MKMapView alloc]initWithFrame:self.view.bounds];
    _mapView.delegate = self;
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate  =self;
    //如果定位服务没打开或者 定位服务的状态不是当程序运行中允许访问定位服务时
    
    if ([CLLocationManager locationServicesEnabled] == NO) {
        
//        判断设置 要不要提醒开启系统定位
        
        if ([[[NSUserDefaults standardUserDefaults]stringForKey:@"isRemindLocation"] isEqualToString:@"YES"] ) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有开启系统定位" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                ;
            }];
            UIAlertAction *setAcion = [UIAlertAction actionWithTitle:@"设置" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
                [[UIApplication sharedApplication] openURL:url];
                
            }];
            [alert addAction:cancleAction];
            [alert addAction:setAcion];
            
            [self presentViewController:alert animated:YES completion:^{
                nil;
            }];
        }
    }
    else if([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];

    }
    
//    if ([CLLocationManager locationServicesEnabled] == NO || [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
//        //请求定位服务授权
//        [_locationManager requestWhenInUseAuthorization];
//    }
    //用户位置追踪 (用来标记当前位置, 此时会调用定位服务)
    _mapView.userTrackingMode = MKUserTrackingModeFollow;
    //设置地图的类型
    _mapView.mapType = MKMapTypeStandard;
    //显示用户当前的位置
    _mapView.showsUserLocation = YES;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    
    if ([[UIDevice currentDevice].systemVersion doubleValue] > 9.0){
        [self.locationManager requestLocation];
    }else{
      [self.locationManager startUpdatingLocation];
    }
    
    
    
}


// 在设置中,开启定位后, 回到 应用前台, 去 申请定位权限

#pragma mark --- 定位的代理方法 -- 不断的触发
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *location = [locations firstObject];
    
    _longitude = [NSString stringWithFormat:@"%0.2lf",location.coordinate.longitude];
    _latitude = [NSString stringWithFormat:@"%.2lf",location.coordinate.latitude];
    NSLog(@"当前的地理坐标 >> 经度%@, 纬度%@",_longitude,_latitude);
    
//    上传经度 和 纬度
    if (_longitude > 0 || _longitude < 0) {
        [self.locationManager stopUpdatingLocation];

    }

}
// 返回错误信息
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%@", error);
    
}



//记住密码 按钮
- (void)rememberBTClict{
    
    if (self.loginView.isRememberPassword == NO) {
      
        [self.loginView.rememberBT setBackgroundImage:[UIImage imageNamed:@"register_chk_nor.png"] forState:(UIControlStateNormal)];
        
        [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"isRememberPassword"];

        
        self.loginView.isRememberPassword = YES;
    } else {
          [self.loginView.rememberBT setBackgroundImage:[UIImage imageNamed:@"login_chk_notSec.png"] forState:(UIControlStateNormal)];
        self.loginView.isRememberPassword = NO;
          [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"isRememberPassword"];
    }
}
//登陆
- (void)loginClict{
    

    
//    BSMainInterfaceViewControllerViewController *mainVC = [[BSMainInterfaceViewControllerViewController alloc]init];
//    
//    //获取用户的user_id
//    mainVC.user_id = self.loginView.userNameTF.text;
//    [self.navigationController pushViewController:mainVC animated:YES];

    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
//        dic1[@"userName"]  = @"18500223772";
//        dic1[@"password"] = @"123456";
    dic1[@"userName"]  = self.loginView.userNameTF.text;
    dic1[@"password"] = self.loginView.passwordTF.text;
    dic1[@"grant_type"] = @"password";

//    登陆判定 网络不好 提示正在登录中

    UIAlertView *aaa= [[UIAlertView alloc]initWithTitle:@"正在登陆\n请稍后..." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];;


//    先判断是否输入用户名  和 密码
    if ( ( self.loginView.userNameTF.text != nil && self.loginView.passwordTF.text != nil && ![self.loginView.userNameTF.text  isEqual: @""] && ![self.loginView.passwordTF.text  isEqual: @""] )) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [aaa show];
        });

        [PKRequestManager requestWithUrlString:NetStr parDic:dic1 appendingString:@"/api/User/Login" method:POST finish:^(NSData *data) {
            
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
//            NSLog(@"%@",dic);
//            NSLog(@"%@",dic[@"Code"]);
            if ( dic[@"access_token" ]) {
                //            登陆成功 进入登陆界面
                [aaa dismissWithClickedButtonIndex:0 animated:YES];
                
                
                _isLogin = YES;
                //    先判断用户名和密码是不是正确 包括各式 和  匹配
                [self creatDatabase];
                //  登陆先判断此人是否已经记录
                
                FMResultSet *rs = [_db executeQuery:@"SELECT user_id,password FROM UserInformationlist"];
                while ([rs next]) {
                    NSString *user_id = [rs stringForColumn:@"user_id"];
                    _isExist = [user_id isEqualToString:self.loginView.userNameTF.text];
                    if (_isExist) {
                        break;
                    }
                }
                if (_isExist) {
                    NSLog(@"这个人已经在了");
                } else {
                    NSLog(@"这个人不存在");
                }
                /**           **       */
                
                //    再点击登录的时候 判定 用户是选择记住账号 还是 记住账号和密码
                
                if (self.loginView.isRememberPassword == NO) {
                    /**  只记住账号  **/
                    
                    //        先判断这个账号存不存在 存在就算了 不存在就插入一个新的目录
                    if (_isExist) {
                        NSLog(@"此人已经存在 ,算了");
                        // 如果之前登陆过记住密码 现在又不记住密码了 还要删除对应的密码
                        [_db executeUpdate:@"update  UserInformationlist set password = ? where user_id = ?",nil,self.loginView.userNameTF.text];
                    } else {
                        //此人不存在 加入
                        [_db executeUpdate:@"INSERT INTO UserInformationlist (user_id) VALUES (?)",self.loginView.userNameTF.text];
                    }
                } else {//记住账户密码
                    //同样要判断此人是否已经存在
                    if (_isExist) {
                        //用户选择记住密码 需要在本地存储密码
                        [_db executeUpdate:@"update  UserInformationlist set password = ? where user_id = ?",self.loginView.passwordTF.text,self.loginView.userNameTF.text];
                        
                    } else {
                        //此人不存在 加入
                        [_db executeUpdate:@"INSERT INTO UserInformationlist (user_id, password) VALUES (?,?)",self.loginView.userNameTF.text,self.loginView.passwordTF.text];
                    }
                }
//              用于记住密码
                [[NSUserDefaults standardUserDefaults] setObject:self.loginView.userNameTF.text forKey:@"lastPerson"];
                
                
                
                BSMainInterfaceViewControllerViewController *mainVC = [[BSMainInterfaceViewControllerViewController alloc]init];
                
                //获取用户的user_id
                [BSUserSGton userHandle].verifiPhoneNum = dic[@"MobileNum"];
                [BSUserSGton userHandle].user_id = dic[@"UserID"];
                [BSUserSGton userHandle].user_token = dic[@"access_token"];
                [BSUserSGton userHandle].user_loginName =  dic1[@"userName"];
                [BSUserSGton userHandle].user_loginName = [[BSUserSGton userHandle].user_loginName stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];

               [self getInformation];
//                登陆成功 保存token
                [_db executeUpdate:@"update  UserInformationlist set token = ? where user_id = ?",dic[@"access_token"],self.loginView.userNameTF.text];


                [BSUserSGton userHandle].memoryValue = [BSUserSGton freeDiskSpaceInBytes];
                
                
                mainVC.GPSLA = _latitude;
                mainVC.GpsLO = _longitude;
                
                mainVC.user_id = dic[@"UserID"];
                [BSUserSGton userHandle].isLogin = YES;;
                [self.navigationController pushViewController:mainVC animated:YES];
                
            }else{
                
  
                [aaa dismissWithClickedButtonIndex:0 animated:YES];

                [PKRequestManager showAlertView:@"用户名或密码不正确"];
            
            }
            
        } error:^(NSError *error) {
            NSLog(@"网络请求错误");
            [aaa dismissWithClickedButtonIndex:0 animated:YES];
            
#pragma mark  因为网络问题 导致连接失败 判断是否要离线登陆 
//            以前登陆成功过 且保存了密码才能使用离线登录功能
            FMResultSet *rs = [_db executeQuery:@"SELECT password FROM UserInformationlist where user_id = ?",self.loginView.userNameTF.text];
            while ([rs next]) {
                NSString *password = [rs stringForColumn:@"password"];
                _isExist = [password isEqualToString:self.loginView.passwordTF.text];
                if (_isExist) {
                    [self offlineLogin];
                }
            }
        
            
        }];

    } else {
        [PKRequestManager showAlertView:@"请输入用户名和密码"];
    }
    
    
    
  


 
/*   test   */
    
//    TripleECGViewController *tripleVC = [[TripleECGViewController alloc]init];
//    [self.navigationController pushViewController:tripleVC animated:YES];
}
- (void)registerBTClict{
    
    
    BSRegisterViewController *registVC = [[BSRegisterViewController alloc]init];
    
//    registVC.modalInPopover = YES;
    registVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    
    [self presentViewController:registVC animated:YES completion:^{
        nil;
    }];
   }

- (void)forgetPassword{

    BSForgetPasswordViewController *forPasswordVC = [[BSForgetPasswordViewController alloc]init];
    [self presentViewController:forPasswordVC animated:YES completion:nil];
    
}


- (void)faildLogin:(UIAlertView *)alert{

    if (_isLogin == NO) {
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        [PKRequestManager showAlertView:@"登录失败"];
    }
}

- (void)viewWillAppear:(BOOL)animated{

    self.navigationItem.hidesBackButton = YES;

    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"CreatSQL"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"CreatSQL"];
        [self creatDatabase];

    }else {
         }
    
    
    if ([[[NSUserDefaults standardUserDefaults]stringForKey:@"isRememberPassword"] isEqualToString:@"YES"] ) {
        
        [self.loginView.rememberBT setBackgroundImage:[UIImage imageNamed:@"register_chk_nor.png"] forState:(UIControlStateNormal)];
 
        self.loginView.isRememberPassword = YES;

    }
    
}
- (void)viewWillDisappear:(BOOL)animated{


}

- (void)viewDidAppear:(BOOL)animated{
    [self getLocationCoordinate];
    
#pragma mark 实现记住密码功能 和 自动那个登陆
    
    //  创建我们的数据库的路径 同时拼接数据库的文件名称
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"FMDataBase.db"];
//    NSLog(@">> 地址%@",path);
    
    //  根据路径去创建一个数据库
    _db = [FMDatabase databaseWithPath:path];
    //    先保存上一个人得用户名
    [_db open];

    
    if(![[NSUserDefaults standardUserDefaults] stringForKey:@"lastPerson"]) {
//        [[NSUserDefaults standardUserDefaults] setObject:self.loginView.userNameTF.text forKey:@"lastPerson"];
//        NSLog(@"存的上一个人");
        
    }else{
        //      上一个登陆的人
        NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastPerson"];
        //      取出这个人的密码
        
//        NSString *address = [db stringForQuery:@"SELECT Address FROM PersonList WHERE Name = ?",@"John”];
//        FMResultSet *rs = [_db executeQuery:@"SELECT user_id,password FROM UserInformationlist"];
        FMResultSet *rs = [_db executeQuery:@"SELECT password FROM UserInformationlist WHERE user_id = ?",userName];
        
        while ([rs next]) {
            NSString *password = [rs stringForColumn:@"password"];

            self.loginView.userNameTF.text = userName;
            self.loginView.passwordTF.text = password;

        }

    }
    

}

- (void)creatDatabase{
    //  创建我们的数据库的路径 同时拼接数据库的文件名称
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"FMDataBase.db"];
    
    NSLog(@"数据库表的位置 >> %@",path);
    
    //  根据路径去创建一个数据库
    _db = [FMDatabase databaseWithPath:path];
    //    NSLog(@"%@",path);
    
    //  调用open方法 打开成功返回YES 失败 返回NO
    if ([_db open]) {
        NSLog(@"数据库打开成功");
    }else
    {
        NSLog(@"数据库打开失败");
    }
    
    //  调用db的executeUpdata 这个方法的参数就是SQL 语句
    [_db executeUpdate:@"CREATE TABLE UserInformationlist (isLogin text, user_id text, password text, token text, DeviceID text,UUID text)"];

}

- (void)viewDidDisappear:(BOOL)animated{
#pragma mark  既然登陆成功了 也就获取了user_id 顺便上传 地理信息
    
    NSString *user_id = [BSUserSGton userHandle].user_id;;
    
    [PKRequestManager InserGPSWithnetUrl:NetStr userID:user_id gPSLo:_longitude gPSLa:_latitude method:POST finish:^(NSData *data) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
//        NSLog(@"%@",dic);
        
    } error:^(NSError *error) {
        ;
    }];
  
}
//离线登录
- (void)offlineLogin{

    
    {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"离线登录" message:@"是否确认离线登录" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            BSMainInterfaceViewControllerViewController *mainVC = [[BSMainInterfaceViewControllerViewController alloc]init];
            mainVC.user_id = self.loginView.userNameTF.text;
            [BSUserSGton userHandle].user_loginName = self.loginView.userNameTF.text;
#pragma mark 对logName 进行处理
            [BSUserSGton userHandle].user_loginName = [[BSUserSGton userHandle].user_loginName stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            
            [BSUserSGton userHandle].isLogin = YES;
            
//            离线登录 需要取出这个人保存在本地的信息
            
            [_db executeUpdate:@"CREATE TABLE UserInformationlist (isLogin text, user_id text, password text, token text, DeviceID text,UUID text)"];

            
            FMResultSet *rs = [_db executeQuery:@"SELECT * FROM UserInformationlist WHERE user_id = ?",self.loginView.userNameTF.text];
            
            while ([rs next]) {
                NSString *token = [rs stringForColumn:@"token"];
                NSString *UUID = [rs stringForColumn:@"UUID"];
                NSString *DeviceID = [rs stringForColumn:@"DeviceID"];

 
                [BSUserSGton userHandle].DeviceID = DeviceID;
                [BSUserSGton userHandle].user_token = token ;
                [BSBluetoothSingleton shareBlutooth].uuiduuid = UUID;
            }
            
            
            [self.navigationController pushViewController:mainVC animated:YES];
            

        }];
        UIAlertAction *setAcion = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        [alert addAction:cancleAction];
        [alert addAction:setAcion];
        
        [self presentViewController:alert animated:YES completion:^{
            nil;
        }];
    }

}

- (void)getInformation{
        NSString *user_id = [BSUserSGton userHandle].user_id;
        [PKRequestManager GetUserBaseWithnetUrl:NetStr userID:user_id method:POST finish:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            //    根据收到的data  给自己的属性 赋值
            
            //   NSLog(@"%@",dic);
            NSDictionary *dataDic = [NSDictionary dictionaryWithDictionary:dic[@"Data"]];
            BSUIUserInfoBase *userBaseinfoModel = [[BSUIUserInfoBase alloc]init];
            [userBaseinfoModel setValuesForKeysWithDictionary:dataDic];
            [BSUserSGton userHandle].realName = userBaseinfoModel.RealName;
#pragma mark             对真实姓名进行处理
            if ([BSUserSGton userHandle].realName.length > 2) {
                [BSUserSGton userHandle].realName = [userBaseinfoModel.RealName stringByReplacingCharactersInRange:NSMakeRange(1, [BSUserSGton userHandle].realName.length - 2) withString:@"*"];
                
            } else {
                [BSUserSGton userHandle].realName = [userBaseinfoModel.RealName stringByReplacingCharactersInRange:NSMakeRange(1, [BSUserSGton userHandle].realName.length - 1) withString:@"*"];

            }
            
            
          
        } error:^(NSError *error) {
            ;
        }];
        


    
    
}

// 监测网络状态 用于WiFi上传
- (void)AFNetworkStatus{
    
    //1.创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    /*枚举里面四个状态  分别对应 未知 无网络 数据 WiFi
     typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
     AFNetworkReachabilityStatusUnknown          = -1,      未知
     AFNetworkReachabilityStatusNotReachable     = 0,       无网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,       蜂窝数据网络
     AFNetworkReachabilityStatusReachableViaWiFi = 2,       WiFi
     };
     */
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //这里是监测到网络改变的block  可以写成switch方便
        //在里面可以随便写事件
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络状态");
                
                [BSUserSGton userHandle].netstatus = @"Unknown";
                
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                 [BSUserSGton userHandle].netstatus = @"NoNet";
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据网");
                 [BSUserSGton userHandle].netstatus = @"cellulardData";
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi网络");
                   [BSUserSGton userHandle].netstatus = @"WIFI";
                break;
                
            default:
                break;
        }
        
    }] ;
    
    [manager startMonitoring];
}
//改变textfeild的高度
- (void)keyBoardWillChangeFrame:(NSNotification *)notification{
    [super keyBoardWillChangeFrame:notification];

//self.keybordHeight
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
